import requests,markdown
import json,time

def get_access_token():
    APIKEY="BWN9pwIZx6aoSjhSeGEiFikd"
    secret_key="1cNeE3iG2czhcRtjsLrEuOul100bxKNI"
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def genai(token,ingredients,theme):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content": "你擅长制作全球各国风味的创意菜肴。请为您的客人制作一道%s，以%s为原料的菜肴。输出内容包含简介、所需材料、准备时间、烹饪时间、难度等级（1-5级，从简单到困难）、营养成分表（包括卡路里）、制作步骤、菜肴特点这几段内容。其它内容不许提。"%(theme,ingredients)
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return None
    result = json.loads(response.text)
    if 'result' not in result: return None
    return markdown.markdown(result['result']).replace('"','').replace('\r','\n').replace('\n','&nbsp;&nbsp;')
